import { http } from "@/utils/http";
import { SupplierQuery, SupplierRequest, SupplierVO } from "@/types/attendance/supplier/index";
import { ResponseData } from "@/types/common/response";
import { AxiosPromise } from "axios";

/**
 * 获取供应商列表
 */
export function getSupplierList(
  query: SupplierQuery
): Promise<ResponseData<{ rows: SupplierVO[]; total: number }>> {
  // 过滤掉空字符串参数，避免后端处理成%%的问题
  const filteredParams = Object.entries(query).reduce((acc, [key, value]) => {
    // 只保留非空字符串或非零数值的参数
    if (value !== "" && value !== null && value !== undefined) {
      acc[key] = value;
    }
    return acc;
  }, {} as Record<string, any>);

  // 确保分页参数存在
  const params = {
    ...filteredParams,
    pageNum: query.pageNum || 1,
    pageSize: query.pageSize || 10
  };

  console.log("供应商查询API请求参数(过滤后):", params);

  // 添加完整请求路径日志
  console.log(
    "完整请求URL:",
    `/attendance/supplier/list?${new URLSearchParams(params as any).toString()}`
  );

  // 监听请求返回结果
  return http
    .get<any, ResponseData<{ rows: SupplierVO[]; total: number }>>("/attendance/supplier/list", {
      params
    })
    .then(res => {
      console.log("供应商列表API返回结果:", res);
      return res;
    })
    .catch(err => {
      console.error("供应商列表API请求失败:", err);
      throw err;
    });
}

/**
 * 获取供应商详情
 */
export function getSupplierDetail(supplierId: number | string): Promise<ResponseData<SupplierVO>> {
  return http.get<any, ResponseData<SupplierVO>>(`/attendance/supplier/${supplierId}`);
}

/**
 * 新增供应商
 */
export function addSupplier(data: SupplierRequest): Promise<ResponseData<void>> {
  return http.post<any, ResponseData<void>>("/attendance/supplier", { data });
}

/**
 * 修改供应商
 */
export function updateSupplier(data: SupplierRequest): AxiosPromise<ResponseData<void>> {
  return http.request("put", "/attendance/supplier", { data });
}

/**
 * 删除供应商
 */
export function deleteSupplier(supplierIds: number[] | string[]): Promise<any> {
  console.log("删除接口，传入参数:", supplierIds);

  return http
    .request("delete", "/attendance/supplier", {
      data: { items: supplierIds }
    })
    .then(res => {
      console.log("删除接口，返回结果:", res);
      return res;
    })
    .catch(err => {
      console.error("删除接口，错误:", err);
      throw err;
    });
}

/**
 * 更新供应商状态
 */
export function updateSupplierStatus(
  supplierId: number,
  status: string
): AxiosPromise<ResponseData<void>> {
  return http.request("put", `/attendance/supplier/status/${supplierId}`, {
    data: { status }
  });
}

/**
 * 获取供应商联系人列表
 */
export function getSupplierContacts(supplierId: number): Promise<ResponseData<any[]>> {
  return http.get<any, ResponseData<any[]>>(`/attendance/supplier/${supplierId}/contacts`);
}

/**
 * 添加供应商联系人
 */
export function addSupplierContact(
  supplierId: number,
  data: { name: string; phone: string; email: string; position: string }
): Promise<ResponseData<void>> {
  return http.post<any, ResponseData<void>>(`/attendance/supplier/${supplierId}/contacts`, {
    data
  });
}

/**
 * 修改供应商联系人
 */
export function updateSupplierContact(
  supplierId: number,
  contactId: number,
  data: { name: string; phone: string; email: string; position: string }
): AxiosPromise<ResponseData<void>> {
  return http.request("put", `/attendance/supplier/${supplierId}/contacts/${contactId}`, { data });
}

/**
 * 删除供应商联系人
 */
export function deleteSupplierContact(
  supplierId: number,
  contactId: number
): AxiosPromise<ResponseData<void>> {
  return http.request("delete", `/attendance/supplier/${supplierId}/contacts/${contactId}`);
}

/**
 * 导出供应商数据
 */
export function exportSupplier(query: SupplierQuery) {
  console.log("导出供应商数据，查询参数:", query);
  return http.download("/attendance/supplier/export", "供应商列表.xlsx", {
    params: query
  });
}

/**
 * 下载导入模板
 */
export function downloadImportTemplate() {
  return http.get("/attendance/supplier/importTemplate", {
    responseType: "blob"
  });
}

/**
 * 导入供应商
 */
export function importSupplier(file: File) {
  const formData = new FormData();
  formData.append("file", file);
  return http.request("post", "/attendance/supplier/import", {
    data: formData,
    headers: { "Content-Type": "multipart/form-data" }
  });
}

/**
 * 批量删除供应商
 */
export function batchDeleteSuppliers(supplierIds: number[]): AxiosPromise<ResponseData<void>> {
  return http.request("delete", "/attendance/supplier/batch", {
    data: { supplierIds }
  });
}

/**
 * 更新供应商评分
 */
export function updateSupplierScore(supplierId: number, score: number) {
  return http.request("put", `/attendance/supplier/${supplierId}/score`, {
    data: { score }
  });
}

/**
 * 获取供应商分类列表
 */
export function getSupplierCategories(): Promise<ResponseData<any[]>> {
  return http.get<any, ResponseData<any[]>>("/attendance/supplier/categories");
}

/**
 * 更新供应商分类
 */
export function updateSupplierCategory(
  supplierId: number,
  categoryId: number
): AxiosPromise<ResponseData<void>> {
  return http.request("put", `/attendance/supplier/${supplierId}/category`, {
    data: { categoryId }
  });
}
